import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
	history: createWebHistory(import.meta.env.BASE_URL),
	routes: [
		{
			path: '/',
			name: 'moviePage',
			component: () => import('../views/homePage.vue'),
			// 嵌套路由
			children: [
				{
					path: '/',
					name: 'indexPage',
					component: () => import('../views/movie/indexPage.vue')
				},
				{
					path: '/movie',
					name: 'movieTagSearch',
					component: () => import('../views/movie/movieTagSearch.vue')
				},
				{
					path: '/news',
					name: 'newsPage',
					component: () => import('../views/news/newsPage.vue')
				},
				{
					path: '/newsDetails/:id',
					name: 'newsDetails',
					component: () => import('../views/news/newsDetails.vue')
				},
				{
					path: '/movieDetails/:id',
					name: 'movieDetails',
					component: () => import('../views/movie/movieDetails.vue')
				},
				{
					path: '/search',
					name: 'searchPage',
					component: () => import('../views/movie/searchMovie.vue')
				},
				{
					path: '/userInfo',
					name: 'userInfoPage',
					meta: { permission: true },
					component: () => import('../views/users/userInfo.vue')
				},
				{
					path: '/userMail',
					name: 'userMailPage',
					meta: { permission: true },
					component: () => import('../views/users/userMail.vue')
				},
				{
					path: '/userComment',
					name: 'userCommentPage',
					meta: { permission: true },
					component: () => import('../views/users/userComment.vue')
				},
				{
					path: '/userFavorite',
					name: 'userFavoritePage',
					meta: { permission: true },
					component: () => import('../views/users/userFavorite.vue')
				},
				{
					path: '/userSpace/:id',
					name: 'userSpace',
					component: () => import('../views/users/userSpace.vue')
				}
			]
		},
		{
			path: '/login',
			name: 'login',
			// 单独的路由守卫
			// eslint-disable-next-line no-unused-vars
			beforeEnter: (to, from) => {
				if (localStorage.getItem('token')) {
					AMessage.success('已登录~~~')
					return router.push('/')
				}
				return true
			},
			component: () => import('../views/users/LoginPage.vue')
		},
		{
			path: '/register',
			name: 'register',
			// 单独的路由守卫
			// eslint-disable-next-line no-unused-vars
			beforeEnter: (to, from) => {
				if (localStorage.getItem('token')) {
					AMessage.success('已登录~~~')
					return router.push('/')
				}
				return true
			},
			component: () => import('../views/users/registerPage.vue')
		}
	]
})
// 路由守卫 判断是否登录
router.beforeEach((to, from, next) => {
	if (to.meta.permission) {
		if (localStorage.getItem('token')) {
			next()
		} else {
			AMessage.error('请先登录!!!')
			next('/login')
		}
	} else {
		next()
	}
})
export default router
